import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getToken, setToken } from './storage'
import history from './history'
import store from '@/store'
import { logout, setTokenInfo } from '@/store/actions/login'
export const baseLink = 'http://geek.itheima.net'

// 1. 创建新的 axios 实例
const http = axios.create({
  baseURL: baseLink + '/v1_0',
})

// 2. 设置请求拦截器和响应拦截器
http.interceptors.request.use((config) => {
  const token = getToken().token || ''
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

http.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    const { config } = error
    if (error?.response?.status === 401) {

      const { token, refresh_token } = getToken()
      if (!token || !refresh_token) {
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname,
          },
        })
        return Promise.reject(error)
      }
      // 不要使用http实例来发请求 不然会走拦截器
      try {
        const res = await axios.put(
          config.baseURL + '/authorizations',
          {},
          {
            headers: {
              Authorization: `Bearer ${refresh_token}`,
            },
          }
        )
        const newToken = res.data.data.token
        // 保存到本地
        setToken({ token: newToken, refresh_token })
        // 保存到redux
        store.dispatch(setTokenInfo({ token: newToken, refresh_token }))
        // 重新发起原先的请求
        return http(config)
      } catch (err) {
        // refresh_token 也过期
        store.dispatch(logout())
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname,
          },
        })
        return Promise.reject(error)
      }
    }

    if (error?.response?.data?.message) {
      Toast.fail(error.response.data.message)
    } else {
      Toast.fail('系统繁忙')
    }
    return Promise.reject(error)
  }
)

// 3. 导出该 axios 实例
export default http
